/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yhao.infra.apilist.JsonCommonCodeEnum;
import yhao.infra.web.common.util.CommonWebUtil;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 内部请求ip限制拦截器
 *
 * <p>用在微服务之间的调用，仅允许内网ip访问
 *
 * @author yoara
 */
public class InnerAccessCheckFilter implements Filter {
    public final static String DEFAULT_IP_PREFIX = "10.251.92.";
    private Logger visitLog = LoggerFactory.getLogger(this.getClass());
    private boolean check;
    private String ipPrefix = DEFAULT_IP_PREFIX;
    private String[] ipPrefixGroup = {ipPrefix};

    public InnerAccessCheckFilter(boolean check,String ipPrefixs) {
        this.check = check;
        setIpPrefix(ipPrefixs);
    }

    public void setIpPrefix(String ipPrefix) {
        this.ipPrefix = ipPrefix;
        this.ipPrefixGroup = StringUtils.split(ipPrefix,",");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(!check){
            chain.doFilter(request,response);
            return;
        }
        HttpServletRequest req = (HttpServletRequest)request;
        if (!checkIp(req)) {
            CommonWebUtil.ResponseBody body = new CommonWebUtil.ResponseBody();
            body.setCode(JsonCommonCodeEnum.E0017);
            String ips = StringUtils.join(CommonWebUtil.getIpAddr(req), ",");
            body.setMessage(ips + body.getMessage());
            visitLog.error(body.getMessage());
            CommonWebUtil.printJsonMsg((HttpServletResponse)response, body);
            return;
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {}

    private boolean checkIp(HttpServletRequest request) {
        String[] ips = CommonWebUtil.getIpAddr(request);
        for(String ip:ips){
            for(String ipWhite:ipPrefixGroup){
                if(ip.trim().startsWith(ipWhite)){
                    return true;
                }
            }
        }
        return false;
    }
}
